package com.woniuxy.lrz.carlproject.service.impl;

import cn.dev33.satoken.stp.SaLoginConfig;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.lrz.carlproject.common.AppException;
import com.woniuxy.lrz.carlproject.controller.form.userform.*;
import com.woniuxy.lrz.carlproject.dao.CarDetailMapper;
import com.woniuxy.lrz.carlproject.dao.ReceiveAddressMapper;
import com.woniuxy.lrz.carlproject.dao.UserCarMapper;
import com.woniuxy.lrz.carlproject.model.CarDetail;
import com.woniuxy.lrz.carlproject.model.ReceiveAddress;
import com.woniuxy.lrz.carlproject.model.User;
import com.woniuxy.lrz.carlproject.dao.UserMapper;
import com.woniuxy.lrz.carlproject.model.UserCar;
import com.woniuxy.lrz.carlproject.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.lrz.carlproject.service.dto.userdto.CarDetailDTO;
import com.woniuxy.lrz.carlproject.service.dto.userdto.LoginDTO;
import com.woniuxy.lrz.carlproject.service.dto.userdto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author lrz
 * @since 2022-09-28
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private UserMapper userMapper;
    @Resource
    private ReceiveAddressMapper addressMapper;
    @Resource
    private UserCarMapper carMapper;
    @Resource
    private CarDetailMapper carDetailMapper;

    //获取验证码 有效期60s
    public String getCheckCode(String phone) {
        String randomCode = RandomUtil.randomNumbers(6);
        RBucket<String> checkCode = redissonClient.getBucket("checkCode");
        checkCode.set(randomCode,100, TimeUnit.SECONDS);
        return randomCode;
    }

    //用户注册
    public void userRegister(RegisterForm registerForm) {
        //判断校验码是否正确
        RBucket<String> checkCode = redissonClient.getBucket("checkCode");
        if(!checkCode.clearExpire()){
            throw new AppException("验证码已过期,请重新获取");
        }
        String cc = checkCode.get();
        log.info("cc:{}",cc);
        if(!cc.equals(registerForm.getCheckCode())){
            throw new AppException("验证码错误,请重新输入");
        }
        //用户是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",registerForm.getPhone());
        User user1 = userMapper.selectOne(wrapper);
        if(user1!=null){
            throw new AppException("用户已存在，请勿重复注册");
        }
        String hashPass = DigestUtils.sha256Hex(registerForm.getPassword());
        log.info("hashPss:{}",hashPass);
        User user = BeanUtil.copyProperties(registerForm, User.class);
        user.setPassword(hashPass);
        user.setCreateTime(new Date());
        user.setUsername(registerForm.getPhone());
        user.setStatus("NORMAL");
        user.setNickname(RandomUtil.randomString(4));
        user.setImagePhoto("https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png");
        int insert = userMapper.insert(user);
    }

    //登录
    public LoginDTO userLogin(LoginForm loginForm) {
        String hashPass = DigestUtils.sha256Hex(loginForm.getPassword());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",loginForm.getPhone());
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            throw new AppException("该用户尚未注册");
        }
        if(!user.getPassword().equals(hashPass)){
            throw new AppException("密码输入错误");
        }
        int userId = user.getUserId();
        StpUtil.login(userId, SaLoginConfig.setExtra("username",user.getUsername()));
        LoginDTO loginDTO = new LoginDTO(userId, StpUtil.getTokenValue());
        return loginDTO;
    }

    //获取用户普通信息
    public UserInfoDTO getUserInfo() {
        Integer userId = Integer.parseInt((String)StpUtil.getLoginId());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        User user = userMapper.selectOne(wrapper);
        if(user==null){
            throw new AppException("该用户尚未注册");
        }
        UserInfoDTO userInfoDTO = BeanUtil.copyProperties(user, UserInfoDTO.class);
        return userInfoDTO;
    }

    //修改个人信息
    public void updateUserInfo(ModifyInfoForm modifyInfoForm) {
        User user = BeanUtil.copyProperties(modifyInfoForm, User.class);
        user.setUserId(Integer.parseInt((String)StpUtil.getLoginId()));
        int i = userMapper.updateById(user);
    }

    //修改用户头像
    public void updateUserImage(Integer loginId, String url) {
        User user = new User();
        user.setUserId(loginId);
        user.setImagePhoto(url);
        int i = userMapper.updateById(user);
    }

    //添加用户收货地址========================================================
    @Transactional
    public void addReceiveAddress(ReceiveAddressForm receiveAddressForm) {
        //最多只能添加5个收货地址
        ArrayList<ReceiveAddress> receiveAddressList = getReceiveAddress();
        if(receiveAddressList !=null && receiveAddressList.size()==5){
            throw new AppException("最多只能添加5个收货地址");
        }

        Integer userId = Integer.parseInt((String)StpUtil.getLoginId());
        //如果新增地址为选中，则更改之前选中地址状态
        if(receiveAddressForm.getIsChoose().equals("1")){
            QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            wrapper.eq("is_choose","1");
            ReceiveAddress receiveAddress = addressMapper.selectOne(wrapper);
            if(receiveAddress!=null){
                Integer receiveAddressId = receiveAddress.getReceiveAddressId();
                ReceiveAddress receiveAddress1 = new ReceiveAddress();
                receiveAddress1.setReceiveAddressId(receiveAddressId);
                receiveAddress1.setIsChoose("0");
                int i = addressMapper.updateById(receiveAddress1);
            }
        }
        //添加收货地址
        ReceiveAddress receiveAddress = BeanUtil.copyProperties(receiveAddressForm, ReceiveAddress.class);
        receiveAddress.setUserId(userId);
        int insert = addressMapper.insert(receiveAddress);
    }

    //修改收货地址
    public void updateReceiveAddress(ReceiveAddressForm2 receiveAddressForm) {
        Integer userId = Integer.parseInt((String)StpUtil.getLoginId());
        //修改为选中
        if(receiveAddressForm.getIsChoose().equals("1")){
            QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id",userId);
            wrapper.eq("is_choose","1");
            ReceiveAddress receiveAddress = addressMapper.selectOne(wrapper);
            if(receiveAddress!=null){//改变其他选中地址状态
                Integer receiveAddressId = receiveAddress.getReceiveAddressId();
                ReceiveAddress receiveAddress1 = new ReceiveAddress();
                receiveAddress1.setReceiveAddressId(receiveAddressId);
                receiveAddress1.setIsChoose("0");
                int i = addressMapper.updateById(receiveAddress1);
            }
        }
        //修改当前提交地址
        ReceiveAddress receiveAddress = BeanUtil.copyProperties(receiveAddressForm, ReceiveAddress.class);
        int i = addressMapper.updateById(receiveAddress);
    }

    //删除收货地址
    public void deleteReceiveAddress(Integer receiveAddressId) {
        int i = addressMapper.deleteById(receiveAddressId);
    }

    //查询收货地址
    public ArrayList<ReceiveAddress> getReceiveAddress() {
        QueryWrapper<ReceiveAddress> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",Integer.parseInt((String)StpUtil.getLoginId()));
        ArrayList<ReceiveAddress> addressList = (ArrayList)addressMapper.selectList(wrapper);
        if(addressList==null || addressList.size()==0){
            throw new AppException("赞无收货地址");
        }
        return addressList;
    }

    //添加用户用车====================================================
    public void addMyCar(AddCarForm addCarForm) {
        Integer userId = Integer.parseInt((String) StpUtil.getLoginId());
        //修改之前选中用车的状态
        QueryWrapper<UserCar> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("user_id",userId);
        wrapper2.eq("status","CURRENT");
        UserCar userCar1 = carMapper.selectOne(wrapper2);
        if(userCar1!=null){
            userCar1.setStatus("WAITTING");
            int i = carMapper.updateById(userCar1);
        }
        //限制最多添加5台用车
        QueryWrapper<UserCar> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<UserCar> cars = carMapper.selectList(wrapper);
        if(cars != null && cars.size()==5){
            throw new AppException("最多只能添加 5台用车信息");
        }
        UserCar userCar = BeanUtil.copyProperties(addCarForm, UserCar.class);
        userCar.setUserId(Integer.parseInt((String)StpUtil.getLoginId()));
        int insert = carMapper.insert(userCar);
    }

    //查询用户用车
    public List<CarDetailDTO> getMyCars() {
        Integer id = Integer.parseInt((String) StpUtil.getLoginId());
        QueryWrapper<UserCar> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",id);
        List<UserCar> cars = carMapper.selectList(wrapper);
        if(cars == null){
            throw new AppException("未添加车辆信息");
        }
        List<CarDetailDTO> carDetails = carMapper.getCarDetails(id);
        return carDetails;
    }

    //删除用户用车
    public void deleteCar(Integer userCarId) {
        int i = carMapper.deleteById(userCarId);
    }

    //设置为当前用车
    @Transactional
    public void setCurrentCar(Integer userCarId) {
        Integer userId = Integer.parseInt((String) StpUtil.getLoginId());
        //修改之前选中用车的状态
        QueryWrapper<UserCar> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        wrapper.eq("status","CURRENT");
        UserCar userCar1 = carMapper.selectOne(wrapper);
        if(userCar1!=null){
            userCar1.setStatus("WAITTING");
            int i = carMapper.updateById(userCar1);
        }
        //修改当前车辆为当前状态
        UserCar userCar = new UserCar();
        userCar.setUserCarId(userCarId);
        userCar.setStatus("CURRENT");
        int i = carMapper.updateById(userCar);
    }

    //修改用车信息
    public void changeCarInfo(ChangeCarForm changeCarForm) {
        UserCar userCar = BeanUtil.copyProperties(changeCarForm, UserCar.class);
        int i = carMapper.updateById(userCar);
    }

    //根据车型详情id获取所有车型详情信息
    public List<CarDetail> getAllCarDetailById(Integer carDetailId) {
        CarDetail carDetail = carDetailMapper.selectById(carDetailId);
        Integer carTypeId = carDetail.getCarTypeId();
        QueryWrapper<CarDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("car_type_id",carTypeId);
        List<CarDetail> carDetails = carDetailMapper.selectList(wrapper);
        return carDetails;
    }
}
